# -*- coding: utf-8 -*-

import time
import math
import wx.richtext

import GUI.gui
import wx
import helpers.tabcontainer
import helpers.wysiwyg
import cStringIO

class NotesView():
    # @type frame GUI.gui.frame_main
    frame = None
    controller = None
    newNoteTabTitle = u"Nová poznámka"
    existingNoteTabTitle = u"Poznámka - "
    booksTabTitle = u"Publikace"
    chooseBookTitle = u"- vybrat publikaci -"
    notePanelVisible = True
    noteBooksPanelVisible = True
    bookNoteIdMap = {}
    noteIdMap = {}
    tagMap = {}
    tabContainer = None
    tabContainerNote = None
    wysiwyg = None


    def __init__(self, controller, frame):
        self.tabContainer = helpers.tabcontainer.TabContainer.getInstance("main")
        self.tabContainerNote = helpers.tabcontainer.TabContainer.getInstance("note")
        self.tabContainerNote.addPanel("basic")
        self.tabContainerNote.addPanel("books")

        self.frame = frame
        self.controller = controller

        self.frame.list_bookNotes.InsertColumn(0, u"Název")
        self.frame.list_bookNotes.InsertColumn(1, u"Tagy")
        self.frame.list_bookNotes.InsertColumn(2, u"Vytvořena")
        self.frame.list_bookNotes.InsertColumn(3, u"Vytvořena kým")
        self.frame.list_bookNotes.InsertColumn(4, u"Změněna")
        self.frame.list_bookNotes.InsertColumn(5, u"Změněna kým")

        self.frame.list_notes.InsertColumn(0, u"Název")
        self.frame.list_notes.InsertColumn(1, u"Publikace")
        self.frame.list_notes.InsertColumn(2, u"Tagy")
        self.frame.list_notes.InsertColumn(3, u"Vytvořena")
        self.frame.list_notes.InsertColumn(4, u"Vytvořena kým")
        self.frame.list_notes.InsertColumn(5, u"Změněna")
        self.frame.list_notes.InsertColumn(6, u"Změněna kým")

        self.frame.Bind(wx.EVT_BUTTON, controller.newAction, frame.button_bookNewNote)
        self.frame.Bind(wx.EVT_BUTTON, controller.newAction, frame.button_notesNewNote)
        self.frame.Bind(wx.EVT_BUTTON, controller.saveAction, frame.button_noteSave)
        self.frame.Bind(wx.EVT_MENU, controller.newAction, frame.menu_fileNewNote)

        self.frame.list_bookNotes.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.onBookNoteActivate)
        self.frame.list_notes.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.onNoteActivate)

        self.frame.hyperlink_noteOpenedBook.Bind(wx.EVT_HYPERLINK, self.onHyperlinkActive)
        self.frame.hyperlink_noteCurrentBook.Bind(wx.EVT_HYPERLINK, self.onHyperlinkCurrent)

        self.wysiwyg = helpers.wysiwyg.Wysiwyg(self.frame.rich_noteContent, self.frame.toolbar_noteContent)

        self.frame.spin_notesPage.Bind(wx.EVT_SPINCTRL, self.controller.updateListAction)
        self.frame.spin_notesPerPage.Bind(wx.EVT_SPINCTRL, self.controller.updateListAction)




    def showNotePanel(self, noteTitle = None):
        tabName = self.newNoteTabTitle
        if noteTitle is not None:
            tabName = self.existingNoteTabTitle + "\"" + noteTitle + "\""

        if self.notePanelVisible == True:
            self.frame.notebook_main.SetPageText(self.tabContainer.getPanelByName("note"), tabName)
            return

        self.frame.notebook_main.InsertPage(self.tabContainer.addPanel("note"), self.frame.panel_note, tabName, True)
        self.frame.panel_note.Show(True)
        self.notePanelVisible = True

    def hideNotePanel(self):
        if self.notePanelVisible == False:
            return
        self.frame.panel_note.Show(False)
        self.frame.notebook_main.RemovePage(self.tabContainer.getPanelByName("note"))
        self.tabContainer.remPanel("note")
        self.notePanelVisible = False

    def resetNotePanel(self):
        self.frame.text_noteName.Clear()
        self.frame.text_noteTags.Clear()
        self.frame.rich_noteContent.Clear()
        self.frame.notebook_book.ChangeSelection(0)
        self.frame.radio_noteBookOpened.Enable(False)
        self.frame.hyperlink_noteOpenedBook.Show(False)

    def focusNotePanel(self):
        if self.notePanelVisible == False:
            return
        
        self.frame.notebook_note.ChangeSelection(0)
        self.frame.notebook_main.ChangeSelection(self.tabContainer.getPanelByName("note"))

    def showNoteBooksPanel(self, noteTitle = None):
        tabName = self.booksTabTitle

        if self.noteBooksPanelVisible == True:
            self.frame.notebook_note.SetPageText(self.tabContainerNote.getPanelByName("books"), tabName)
            return

        self.frame.notebook_note.InsertPage(self.tabContainerNote.addPanel("books"), self.frame.panel_noteBook, tabName, True)
        self.frame.panel_noteBook.Show(True)
        self.noteBooksPanelVisible = True

    def hideNoteBooksPanel(self):
        if self.noteBooksPanelVisible == False:
            return
        self.frame.panel_noteBook.Show(False)
        self.frame.notebook_note.RemovePage(self.tabContainerNote.getPanelByName("books"))
        self.tabContainerNote.remPanel("note")
        self.noteBooksPanelVisible = False

    def resetNoteBooksPanel(self):
        self.frame.radio_noteBookNone.SetValue(True)
        self.frame.hyperlink_noteOpenedBook.Show(False)

    def focusNoteBooksPanel(self):
        if self.noteBooksPanelVisible == False:
            return
        self.frame.notebook_note.ChangeSelection(self.tabContainerNote.getPanelByName("books"))


    def getNoteBasicData(self):
        data = {}
        data["header"] = self.frame.text_noteName.GetValue()
        data["tags"] = self.frame.text_noteTags.GetValue()
        data["body"] = self.getRichtextData()

        return data

    def showError(self, error):
        dialog = wx.MessageDialog(self.frame, error, u"Chyba", wx.OK | wx.ICON_EXCLAMATION)
        dialog.ShowModal()

    def updateBookNotesList(self, notes):
        self.frame.list_bookNotes.DeleteAllItems()

        self.bookNoteIdMap.clear()

        for i, note in enumerate(notes.itervalues()):
            self.bookNoteIdMap[i] = note["id"]
            index = self.frame.list_bookNotes.InsertStringItem(0, note["header"])
            self.frame.list_bookNotes.SetStringItem(index, 1, note["tags"])
            self.frame.list_bookNotes.SetStringItem(index, 2, time.strftime("%d.%m.%Y %H:%S", time.localtime(float(note["cretimestamp"]))))
            self.frame.list_bookNotes.SetStringItem(index, 3, note["creuser"])
            self.frame.list_bookNotes.SetStringItem(index, 4, time.strftime("%d.%m.%Y %H:%S", time.localtime(float(note["modtimestamp"]))))
            self.frame.list_bookNotes.SetStringItem(index, 5, note["moduser"])
            self.frame.list_bookNotes.SetItemData(index,i)


    def setStatus(self, status):
        self.frame.SetStatusText(status)

    def onBookNoteActivate(self, event):
        self.controller.editAction(self.bookNoteIdMap[event.GetData()])

    def setActiveNote(self, note):
        if "header" in note : self.frame.text_noteName.SetValue(note["header"])
        if "tags" in note : self.frame.text_noteTags.SetValue(note["tags"])
        if "body" in note : self.setRichtextData(note["body"])

    def setActiveBook(self, book):
        if book is not None:
            self.frame.hyperlink_noteOpenedBook.Show(True)
            self.frame.hyperlink_noteOpenedBook.SetLabel(book["name"])
            self.frame.hyperlink_noteOpenedBook.SetVisited(False)
            self.frame.radio_noteBookOpened.Enable(True)
            self.frame.radio_noteBookOpened.SetValue(True)
        else:
            self.frame.hyperlink_noteOpenedBook.Show(False)
            self.frame.radio_noteBookOpened.Enable(False)

    def setCurrentBook(self, book):
        if book is not None:
            self.frame.hyperlink_noteCurrentBook.Show(True)
            self.frame.hyperlink_noteCurrentBook.SetLabel(book["name"])
            self.frame.hyperlink_noteCurrentBook.SetVisited(False)
        else:
            self.frame.hyperlink_noteCurrentBook.SetLabel(self.chooseBookTitle)
            self.frame.hyperlink_noteCurrentBook.SetVisited(False)

    def onHyperlinkActive(self, event):
        self.controller.booksController.editAction(self.controller.activeBookId)

    def onHyperlinkCurrent(self, event):
        self.controller.onHyperlinkCurrent()
        

    def getBookAssignType(self):
        radioGroup = {
            "none" : self.frame.radio_noteBookNone,
            "active" : self.frame.radio_noteBookOpened,
            "other" : self.frame.radio_noteBookOther
            }

        for radio in radioGroup:
            if radioGroup[radio].GetValue() is True:
                return radio
        return None

    def getRichtextData(self):
        handler = wx.richtext.RichTextXMLHandler()
        handler.SetFlags(wx.richtext.RICHTEXT_HANDLER_INCLUDE_STYLESHEET)
        s = cStringIO.StringIO()
        handler.SaveStream(self.frame.rich_noteContent.GetBuffer(), s)
        return s.getvalue()

    def setRichtextData(self, data):
        handler = wx.richtext.RichTextXMLHandler()
        handler.SetFlags(wx.richtext.RICHTEXT_HANDLER_INCLUDE_STYLESHEET)
        s = cStringIO.StringIO(data)
        handler.LoadStream(self.frame.rich_noteContent.GetBuffer(), s)

    def updateNotesPagination(self, noteCount):
        limit = self.frame.spin_notesPerPage.GetValue()
        self.frame.spin_notesPage.SetRange(1, math.ceil(float(noteCount) / float(limit)))
        self.frame.static_notesPageMax.SetLabel("/ " + str(int(math.ceil(float(noteCount) / float(limit)))))

    def getNotesPagination(self):
        ret = {}
        ret["limit"] = self.frame.spin_notesPerPage.GetValue()
        ret["offset"] = (self.frame.spin_notesPage.GetValue() - 1) * ret["limit"]
        return ret

    def updateNotesList(self, notes):
        self.frame.list_notes.DeleteAllItems()

        self.noteIdMap.clear()

        for i, note in enumerate(notes):
            self.noteIdMap[i] = {"id" : note["id"], "book" : note["book_id"]}
            
            index = self.frame.list_notes.InsertStringItem(i, note["header"])
            self.frame.list_notes.SetStringItem(index, 1, note["bookName"])
            self.frame.list_notes.SetStringItem(index, 2, note["tags"])
            self.frame.list_notes.SetStringItem(index, 3, time.strftime("%d.%m.%Y %H:%S", time.localtime(float(note["cretimestamp"]))))
            self.frame.list_notes.SetStringItem(index, 4, note["creuser"])
            self.frame.list_notes.SetStringItem(index, 5, time.strftime("%d.%m.%Y %H:%S", time.localtime(float(note["modtimestamp"]))))
            self.frame.list_notes.SetStringItem(index, 6, note["moduser"])
            self.frame.list_notes.SetItemData(index,i)


    def setStatus(self, status):
        self.frame.SetStatusText(status)

    def onNoteActivate(self, event):
        note = self.noteIdMap[event.GetData()]
        self.controller.editAction(note["id"], note["book"])
